package com.ruikc.study.demo.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtUtils {
    // 使用字符串作为密钥
    private static final String SECRET_KEY = "9a4f2c8d3b7e1a5f8c2d4e6b9a3f7d1e5b8c2a4f6d9e3b7a1c8f5d2e4b9a6f3d";
    // 使用 Keys.secretKeyFor 生成安全的密钥
    private static final long EXPIRATION = 86400000; // 24小时

    public static String generateToken(String username) {
        // 将字符串密钥转换为SecretKey对象
        return Jwts.builder()
                .setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(Keys.hmacShaKeyFor(SECRET_KEY.getBytes()))
                .compact();
    }

    public static Claims parseToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(Keys.hmacShaKeyFor(SECRET_KEY.getBytes()))
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    public static boolean validateToken(String token) {
        try {
            parseToken(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}